const { spawn, exec } = require('child_process');
const Logger = require('../../node_core_logger');
const dateFormat = require('dateformat');
const fs = require('fs');
const mkdirp = require('mkdirp');

function snapshot (req, res, next) {
  let liveUrl = req.query.url;
  let now = new Date()
  var jpgName = dateFormat('yyyy-mm-dd-HH-MM-ss')+'.jpeg';
  mkdirp.sync('screenshots');
  var outPath = `./screenshots/${jpgName}`
  /* windows only */
  // let execCmd = `powershell.exe -Command "${this.config.trans.ffmpeg} -probesize 32768 -i ${liveUrl} -y -vframes 1 -f image2 ${outPath}"`
  let execCmd = `${this.config.trans.ffmpeg} -probesize 32768 -i ${liveUrl} -y -vframes 1 -f image2 ${outPath}`
  // let argv = ['-probesize', 32768, '-i', liveUrl, '-y', '-vframes', 1, '-f', 'image2', '%03d.jpeg']
  var ffmpeg_exec = exec(execCmd);
  console.log('++++++++++++++execCmd++++++++++++++++++++++++++++++')
  console.log(execCmd)
  console.log('++++++++++++++execCmd++++++++++++++++++++++++++++++')
  ffmpeg_exec.on('error', (e) => {
    Logger.ffdebug(e);
  });

  ffmpeg_exec.stdout.on('data', (data) => {
    Logger.ffdebug(`FF输出：${data}`);
  });

  ffmpeg_exec.stderr.on('data', (data) => {
    Logger.ffdebug(`FF输出：${data}`);
  });

  ffmpeg_exec.on('close', (code) => {
    res.setHeader('Access-Control-Allow-Origin', this.config.http.allow_origin);
    res.json({
      imageUrl: jpgName
    })
  });
}
exports.snapshot = snapshot;